<template>
    <el-dialog title="编辑图文"  :close-on-click-modal="false" :visible.sync="show"
     class="dialog_index dialog_banner dialog_image" id="imageText"
    :before-close="cancle">
      <el-form v-loading="loading" class="scroll"  >
        <el-tabs type="card" >
          <el-tab-pane :label="item.site"  v-for="item  in formList" :key="item.id">
            <div class="imageText" v-for="(child, index) in item.data" :key="index">
              <div class="title">
                  <span>图文{{index+1}}</span>
                  <p>
                    <el-button @click="AddImageText(index)" type="search">添加图文</el-button>
                    <el-button @click="delImageText(index)" v-if="item.data.length !== 1">删除图文</el-button>
                    <span class="iconbtn" v-if="item.data.length !== 1">
                      <span @click="index != 0 && ramkUp(index)" :class="{'first': index == 0}"><i class="iconfont icon-rank_up"></i></span>
                      <span @click="item.data.length-1 != index && ramkDown(index)" :class="{'last': item.data.length-1 == index}"><i class="iconfont icon-rank_down"></i></span>
                    </span>
                  </p>
               </div>
              <div class="imgTextItem">
                <el-upload class="upload-image" action="/api/api/general/upload"  multiple
                :on-success="(response, file, fileList) => handleBannerSuccess(response, file, fileList, index)"
                  :on-error="handleBannerError" :before-upload="beforeBannerUpload"
                :show-file-list="false" accept=".jpg,.jpeg,.png " :data="{type:'product_image', imageheight: imgH, imagewidth: imgW}" >
                  <el-button size="small" type="primary" @click="isCloseDrawer(index)">图库选择</el-button> 
                  <el-button slot="trigger" size="small" type="primary">本地上传</el-button>
                  <div class="pop_container">
                    <el-image v-if="child.httpImage" :src="child.httpImage" class="pop_image"></el-image>
                  </div>
                  <p class="tip" v-if="!child.httpImage">建议上传.jpg/.jpeg 格式，且尺寸比例为 4:3，大小≤1M</p>

                </el-upload>
                <div class="inputWord">
                  <el-input v-model="child.title" :placeholder="'标题('+item.site+')（非必填项)'"></el-input>
                  <el-input  v-model="child.description" :placeholder="'描述('+item.site+')（非必填项)'"  
                   type="textarea" resize="none" :rows="6"></el-input>
                </div>
              </div>
              <div class="clearBoth"></div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="search" @click="submitForm" :loading="isRequest">保存</el-button>
        <el-button @click="cancle">取消</el-button>
      </span>
      <Drawer v-show="showDrawer" :type="'product_image'" :show="showDrawer"  @closeDialog="closeDrawerDialog"></Drawer>

    </el-dialog>
</template>

<script>
import Drawer  from '@/components/Gallery/index.vue' 
import { productImageGet, productImagePost } from '@/api/product/productBasic.js'
export default {
  data () {
    return {
      formList: [],
      loading: false,
      imgH: '',
      imgW: '',
      obj: {
        specification_name: '',
        image: '',
        title: '',
        description: ''
      },
      isRequest: false,
      showDrawer: false,
      index: 0
    }
  },
  props: {
    show: Boolean,
    closeDialog:Function,
    id: Number
  },
  watch: {
    show:function(){
      if(this.show){
        this.isRequest = false
        this.getProductImage()
      }
    }
  },
  mounted () {
   
    
  },
   components: { Drawer },
  methods: {
    isCloseDrawer(index) {
      this.showDrawer = true
      this.index = index
    },
    // 图库选择是否显示
    closeDrawerDialog (data) {
      this.showDrawer = !this.showDrawer
      if (data && data.filePathNameHttp) { 
         let list = this.formList
        for (let i = 0; i < list.length; i++){
          let form = list[i].data[this.index]
          form.image = data.filePathName
          form.httpImage = data.filePathNameHttp
        }
      }
    },
    ramkUp(index){
      let list = this.formList
      for(let i = 0; i< list.length; i++){
        let data = list[i].data
        for(let j = 0; j < data.length; j++){
          if(j == index){
            let element = data[j-1]
            this.$set(this.formList[i].data, j-1, data[j])
             this.$set(this.formList[i].data, j, element)
          }
        }
      }
    },
    ramkDown(index){
      let list = this.formList
      for(let i = 0; i< list.length; i++){
        let data = list[i].data
        for(let j = 0; j < data.length; j++){
          if(j == index){
            let element = data[j]
            this.$set(this.formList[i].data, j, data[j+1])
             this.$set(this.formList[i].data, j+1, element)
          }
        }
      }
    },
    AddImageText (index) {
      let list  = this.formList 
      for(let i in list){
        let data =  list[i].data
        let obj = {
          specification_name: '',
          image: '',
          title: '',
          description: '',
          httpImage: '',
          product_id: this.id,
          title_key: '',
          product_basic_id: '',
          site_id: ''
        }
        data.splice(index+1, 0, obj)
      }
      this.formList  = list
    },
    delImageText(index){
      let list  = this.formList 
      for(let i in list){
        let data =  list[i].data
        for(let j = 0; j < data.length; j++  ){
          if(index == j){
            data.splice(j, 1)
          } 
        }
      }
      this.formList  = list
    },
    getProductImage () {
      let params = {
        product_id: this.id
      }
      this.loading = true
      productImageGet(params).then(res=>{
        let list = res.data
        for(let i in list){
          if(list[i].data.length == 0) {
            let obj = {
              specification_name: '',
              image: '',
              title: '',
              description: '',
              httpImage: '',
              product_id: this.id,
              title_key: '',
              product_basic_id: '',
              site_id: ''
            }
            let data = []
            data.push(obj)
            list[i].data = data
          }
          
        } 
        this.formList = list
        this.loading = false

      })
    },
    submitForm () {
      let status = this.validateForm()
      if(status){
        this.updateTag()
      }
    },
    validateForm () {
      let status = true;
      let list  = this.formList 
      for(let i in list){
        let data =  list[i].data
        for(let j = 0; j < data.length; j++  ){
          console.log(data[j], list[i])
          if(data[j].image == ''){
            this.$message.error('站点' + list[i].site + '图文'+ (j +1) +'图片为必填项')
            status = false
            return ;
          }
          // if(data[j].title == ''){
          //   this.$message.error('站点' + list[i].site + '图文'+ (j +1) +'标题为必填项')
          //   status = false
          //   return ;
          // }
        }
      }
      return status
    },
    updateTag () {
      if (!this.isRequest){
        this.isRequest = true
        let list = this.formList
        for(let i = 0; i < list.length; i++){
          let data =  list[i].data
          for(let j = 0; j < data.length; j++){
            data[j].title_key = '图文' + (j+1)
            data[j].product_basic_id = list[i].product_basic_id
            data[j].site_id = list[i].id
          }
        }
        let params = { 
          data: JSON.stringify(list),
          product_id: this.id
        }
        productImagePost(params).then(res=>{
          if(res.state == 1){
            this.$message.success('保存成功')
            this.cancle()
          }
           this.isRequest = false
        })
    
      }
      },
    cancle(){
      this.$emit('closeDialog')
    },
    handleBannerSuccess (response, res, fileList, index) {
      console.log(response, res, fileList)
      let list = this.formList
      for (let i = 0; i < list.length; i++){
        let data = list[i].data[index]
        data.image = response.data.filePathName
        data.httpImage = response.data.filePathNameHttp
      }
      this.$message.success('上传图片成功')   
    },
    
    handleBannerError(){
      this.$message.error('上传图片失败')   
    },

    beforeBannerUpload(file){
      let that = this
      const isLt2M = file.size / 1024  <=  1024;
      if(!isLt2M){
        this.$message.error("上传图片大小不超过1M")
        return false
      }
      if(file.type !== 'image/jpeg' && file.type !== 'image/jpg' ){
        this.$message.error("仅支持.jpg/.jpeg格式的图片")
        return false
      }
      const isSize = new Promise(function(resolve, reject){
        let _URL = window.URL || window.webkitURL;
        let img = new Image();
        img.onload = function() {
          // let valid = img.width/img.height == 4/3 ;
          let valid = true
          valid ? resolve() : reject();
          let imgW = img.width
          let imgH = img.height
          if (imgW > imgH) {
            that.imgW = imgH * 4 / 3
            that.imgH = imgH
          } else if (imgW <=  imgH) {
            that.imgH = imgW * 3 / 4
            that.imgW = imgW
          } 

        }
        img.src = _URL.createObjectURL(file);
      }).then(()=>{

        return file
      }, ()=>{
         that.$message.error('上传图片尺寸为4:3')
        return Promise.reject()
      })
      return isSize
    },
  
  }

}
</script>

<style lang="scss">

</style>